package com.rzjm.api.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rzjm.api.constant.ResponseCode;
import com.rzjm.api.entity.User;
import com.rzjm.api.entity.UserCarList;
import com.rzjm.api.service.UserCarListService;
import com.rzjm.api.service.UserService;
import com.rzjm.api.util.GsonResultBean;
import com.rzjm.api.util.Tools;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;

/**
 *@Author: ZhouWei
 *@Description:  调查问卷相关接口
 *@Date 2018-05-10
 */
@Component
@RestController
@RequestMapping("/car")//url:模块/资源/{}/细分
public class CarController extends BaseController {

    @Resource
    private UserService userService;
    @Resource
    private UserCarListService userCarListService;

    /**
     *  我的车辆列表
     * @param
     * @throws Exception
     */
    @PostMapping(value = "/user/list")
    public JSONObject list(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            logBefore(logger, "car/list 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int pageIndex = jsonRequest.containsKey("pageIndex") ? jsonRequest.getInt("pageIndex") : 0;
            int pageSize = jsonRequest.containsKey("pageSize") ? jsonRequest.getInt("pageSize") : 0;

            List<String> carNames = new ArrayList<>();
            QueryWrapper<UserCarList> qw = new QueryWrapper<>();
            qw.eq("user_id",user_id);
            List<UserCarList> carLists = userCarListService.getPageEntityList(qw,pageIndex,pageSize);
            if(CollUtil.isNotEmpty(carLists)){
                for (UserCarList carList : carLists){
                    carNames.add(carList.getCarNum());
                }
            }
            map.put("cars",carLists);
            map.put("car_names",carNames);

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",carLists.size(),map),false,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 新增车辆
     * @param
     * @throws Exception
     */
    @PostMapping(value = "/add")
    public JSONObject add(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            logBefore(logger, "car/add 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            System.out.println("citizen/detail 接收的参数： "+requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int car_id = jsonRequest.containsKey("car_id") ? jsonRequest.getInt("car_id") : 0;
            String car_num = jsonRequest.containsKey("car_num") ? jsonRequest.getStr("car_num") : "";
            String real_name = jsonRequest.containsKey("real_name") ? jsonRequest.getStr("real_name") : "";
            String phone_num = jsonRequest.containsKey("phone_num") ? jsonRequest.getStr("phone_num") : "";

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            QueryWrapper<UserCarList> qw = new QueryWrapper<>();
            qw.eq("user_id",user_id);
            qw.eq("car_num",car_num);
            UserCarList carList = userCarListService.getOne(qw);
            if(carList != null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您已添加改车辆"),true,true);
            }

            carList = new UserCarList();
            carList.setUserId(user_id);
            carList.setState(1);
            carList.setCarNum(car_num);
            carList.setCreateTime(new Date());
            carList.setPhoneNum(phone_num);
            carList.setRealName(real_name);
            boolean bl = userCarListService.save(carList);
            if(bl) {
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"添加成功"),true,true);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"添加失败，请重试"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 修改车辆
     * @param
     * @throws Exception
     */
    @PostMapping(value = "/edit")
    public JSONObject edit(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            logBefore(logger, "car/edit 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            System.out.println("citizen/detail 接收的参数： "+requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int car_id = jsonRequest.containsKey("car_id") ? jsonRequest.getInt("car_id") : 0;
            String car_num = jsonRequest.containsKey("car_num") ? jsonRequest.getStr("car_num") : "";
            String real_name = jsonRequest.containsKey("car_num") ? jsonRequest.getStr("real_name") : "";
            String phone_num = jsonRequest.containsKey("phone_num") ? jsonRequest.getStr("phone_num") : "";

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            UserCarList carList = userCarListService.findById(car_id);
            if(carList == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您车辆不存在"),true,true);
            }

            if(user_id != carList.getUserId().intValue()){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您车辆不属于你"),true,true);
            }
            carList.setCarNum(car_num);
            carList.setPhoneNum(phone_num);
            carList.setRealName(real_name);
            boolean bl = userCarListService.updateById(carList);
            if(bl) {
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"修改成功"),true,true);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"修改失败，请重试"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 删除车辆
     * @param
     * @throws Exception
     */
    @PostMapping(value = "/delete")
    public JSONObject delete(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            logBefore(logger, "car/delete 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            System.out.println("citizen/detail 接收的参数： "+requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int car_id = jsonRequest.containsKey("car_id") ? jsonRequest.getInt("car_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            UserCarList carList = userCarListService.findById(car_id);
            if(carList == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您车辆不存在"),true,true);
            }

            if(user_id != carList.getUserId().intValue()){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您车辆不属于你"),true,true);
            }
            boolean bl = userCarListService.removeById(car_id);
            if(bl) {
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"删除成功"),true,true);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"删除失败，请重试"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

}
